package com.datastruct;

/**
 * @author: dong peng
 * @date: 2019/9/27 15:54
 * @description:
 */

public class TokenBucketDemo {
    public long timeStamp = getNowTime();
    public int capacity = 10; // 桶的容量
    public int rate = 3; // 令牌放入速度
    public int tokens=0; // 当前令牌数量

    public static void main(String[] args) throws InterruptedException {
        TokenBucketDemo t = new TokenBucketDemo();

        long tt = System.currentTimeMillis();
        for(int i =0; i < 10000; i++) {
            boolean r = t.grant();
            System.out.println(r);

            if(i % 3 == 0)
            Thread.sleep(1);
        }

        System.out.println(System.currentTimeMillis() - tt);

    }

    public  boolean grant() {
        long now = getNowTime();
        // 先添加令牌
        tokens = (int) Math.min(capacity, tokens + (now - timeStamp) * rate);
        timeStamp = now;
        if (tokens < 1) {
            // 若不到1个令牌,则拒绝
            return false;
        }
        else {
            // 还有令牌，领取令牌
            tokens -= 1;
            return true;
        }
    }

    private long getNowTime() {
        return System.currentTimeMillis()/1000;
    }

}